import { getDepositoryPage } from "@/api/common";
import { addPutStock, getPutStockList } from "@/api/stock/putStock";
import { addDialog } from "@/components/ReDialog";
import { useRouterNavigation } from "@/router/utils";
import { useUserStoreHook } from "@/store/modules/user";
import { dealDataExcept } from "@/utils/common";
import { message } from "@/utils/message";
import { goodsCodeRend, goodsNameRend } from "@/utils/tableColumns";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection, getKeyList } from "@pureadmin/utils";
import dayjs from "dayjs";
import { ElMessageBox } from "element-plus";
import { h, onMounted, reactive, type Ref, ref, watch } from "vue";

// 组件
import { DictTag } from "@/components/common/DictTag";
import { AddPutStock } from "../components";

export function useStoreOrder(tableRef?: Ref) {
  const { push } = useRouterNavigation();

  const isStoreManager = ref(0); // 是否驻店店长角色
  let loginStoreId = useUserStoreHook().loginStoreId;
  let roleList =
    useUserStoreHook().storeList.find(v => v.id == loginStoreId)?.roleList ||
    [];
  if (roleList.some(v => v.roleCode == "shopowner")) {
    isStoreManager.value = 1;
  }

  const selectData = ref({
    ckList: [],
    userList: []
  });
  const totalForm = ref<any>({});
  const form = reactive({
    putInCode: "",
    putInType: "",
    storeOrderCode: "",
    depositoryId: "",
    businessDate: [],
    businessDateBegin: "",
    businessDateEnd: "",
    pageNum: 1,
    pageSize: 20
  });
  const currentTreeData = reactive({
    id: null,
    menuName: ""
  });
  // const formRef = ref();
  const dataList = ref([]);
  const loading = ref(false);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [20, 50, 100, 200],
    background: true
  });
  const tabType = ref(999);
  const tabList = ref([
    { label: "全部", name: 999, count: 0 },
    { label: "待审核", name: 0, count: 0 },
    { label: "发货中", name: 1, count: 0 },
    { label: "部分发货", name: 2, count: 0 },
    { label: "已发货", name: 3, count: 0 },
    { label: "已完成", name: 4, count: 0 },
    { label: "已驳回", name: 5, count: 0 },
    { label: "已取消", name: 6, count: 0 },
    { label: "已关闭", name: 7, count: 0 }
  ]);
  const columns: TableColumnList = [
    {
      type: "expand",
      slot: "expand",
      fixed: "left",
      width: "30px"
    },
    {
      label: "业务日期",
      prop: "businessDate",
      width: 120,
      align: "left",
      fixed: "left",
      formatter: ({ businessDate }) => dayjs(businessDate).format("YYYY-MM-DD")
    },
    {
      label: "入库单编码",
      prop: "putInCode",
      align: "left",
      width: 220
    },
    {
      label: "入库仓库",
      prop: "depositoryName",
      width: 150
    },
    {
      label: "入库商品总数",
      prop: "putInNum",
      width: 120
    },
    {
      label: "入库金额",
      prop: "putInPrice",
      width: 120,
      formatter: ({ putInPrice }) => dealDataExcept(putInPrice)
    },
    {
      label: "业务订单编号",
      prop: "storeOrderCode",
      width: 230
    },
    // 入库类型 1采购 2跨店销售 3换货 4补货
    {
      label: "入库类型",
      prop: "putInType",
      minWidth: 120,
      formatter: ({ putInType }) =>
        putInType == 1
          ? "采购 "
          : putInType == 2
            ? "跨店销售"
            : putInType == 3
              ? "换货"
              : "补货"
    },
    {
      label: "创建人",
      prop: "createUser",
      minWidth: 100
    },
    {
      label: "创建时间",
      prop: "gmtCreate",
      minWidth: 140,
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD HH:mm")
    }
    // {
    //   label: "操作",
    //   align: "left",
    //   fixed: "right",
    //   width: isStoreManager.value == 1 ? 145 : 172,
    //   slot: isStoreManager.value == 1 ? "masterOperation" : "operation"
    // }
  ];

  const childColumns: TableColumnList = [
    {
      label: "商品名称/规格名称",
      prop: "goodsName",
      minWidth: 180,
      align: "left",
      fixed: "left",
      cellRenderer: goodsNameRend
    },
    {
      label: "商品编码/规格编码",
      prop: "goodsCode",
      align: "left",
      minWidth: 150,
      cellRenderer: goodsCodeRend
    },
    {
      label: "商品条码",
      prop: "barCode",
      minWidth: 120,
      formatter: row => row.barCode || "--"
    },
    {
      label: "商品类型",
      prop: "goodsType",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <DictTag dict-type="PRODUCT_TYPE" dict-value={row.goodsType} />
      )
    },
    {
      label: "入库单价",
      prop: "avgBuyPrice",
      minWidth: 100,
      formatter: ({ avgBuyPrice }) => dealDataExcept(avgBuyPrice) || 0
    },
    {
      label: "入库数量",
      prop: "putInNum",
      minWidth: 100
    },
    {
      label: "入库金额",
      prop: "putInPrice",
      minWidth: 100,
      formatter: ({ putInPrice }) => dealDataExcept(putInPrice)
    },
    {
      label: "发货仓",
      prop: "deliveryDepositoryName",
      minWidth: 100,
      formatter: ({ deliveryDepositoryName }) =>
        deliveryDepositoryName || "供应商仓"
    }
  ];

  function handleUpdate(row) {
    console.log(row);
  }

  // 查看商品详情
  const showOrderDetail = row => {
    push({
      path: "/order/store/detail",
      query: { id: row.id }
    });
  };

  // 新增入库
  const addPutStockRef = ref();
  const doPutStock = async () => {
    addDialog({
      title: "新增入库",
      width: "1350px",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(AddPutStock, { ref: addPutStockRef }),
      beforeSure: async (done, { closeLoading }) => {
        let obj = await addPutStockRef.value.confirmPut();
        console.log("params", obj.params);
        if (obj.isPass) {
          addPutStock(obj.params)
            .then(() => {
              message("操作成功", { type: "success" });
              done();
              onSearch();
            })
            .catch(() => closeLoading());
        } else {
          closeLoading();
        }
      },
      beforeCancel: done => {
        done();
      }
    });
  };

  function handleSizeChange(val: number) {
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.pageNum = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量操作 */
  function onBatchStart(goodsStatus) {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const optIds = getKeyList(curSelected, "id");
    console.log("curSelected");
    if (optIds.length <= 0) {
      message("请选择要操作的数据", {
        type: "warning"
      });
    }

    ElMessageBox.confirm(
      `确认要<strong>${goodsStatus == 1 ? "批量启用" : "批量停用"}</strong>选中的商品吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        // await batchUpGoodsStatus({ goodsIds: optIds, goodsStatus });
        tableRef.value.getTableRef().clearSelection();
        onSearch();
        message("操作成功", {
          type: "success"
        });
      })
      .catch(() => {});
  }

  async function onSearch() {
    loading.value = true;

    // 处理请求参数
    let tempForm = { ...form };
    if (tempForm.businessDate && tempForm.businessDate.length > 0) {
      tempForm.businessDateBegin = tempForm.businessDate[0];
      tempForm.businessDateEnd = tempForm.businessDate[1];
    }
    delete tempForm.businessDate;

    const { data } = await getPutStockList(tempForm);
    dataList.value = data.records || [];
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;

    setTimeout(() => {
      loading.value = false;
    }, 200);
  }

  watch(tabType, () => {
    onSearch();
  });

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.storeOrderCode = "";
    form.depositoryId = "";
    form.putInType = "";
    tabType.value = 999;
    form.businessDate = [];
    onSearch();
  };

  onMounted(() => {
    onSearch();

    // 获取仓库列表
    let params = {
      type: 0,
      status: 0,
      pageNum: 1,
      pageSize: 500
    };
    getDepositoryPage(params).then(res => {
      selectData.value.ckList = res.data?.records || [];
    });
  });

  return {
    form,
    loading,
    columns,
    childColumns,
    dataList,
    selectedNum,
    pagination,
    currentTreeData,
    tabType,
    tabList,
    selectData,
    totalForm,
    deviceDetection,
    isStoreManager,
    onSearch,
    resetForm,
    onBatchStart,
    handleUpdate,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onSelectionCancel,
    showOrderDetail,
    doPutStock
  };
}
